<template>
  <div class="equipment-form">
    <el-form
      ref="formRef"
      :model="localEquipment"
      :rules="formRules"
      label-width="120px"
      @submit.prevent
    >
      <el-tabs v-model="activeTab" type="border-card">
        <!-- 基础信息 -->
        <el-tab-pane label="基础信息" name="basic">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="装备ID" prop="id">
                <el-input 
                  v-model="localEquipment.id" 
                  :disabled="mode !== 'create'"
                  placeholder="输入唯一的装备ID"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="装备名称" prop="name">
                <el-input 
                  v-model="localEquipment.name" 
                  placeholder="输入装备名称"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="6">
              <el-form-item label="体系" prop="sys">
                <el-select v-model="localEquipment.sys" placeholder="选择体系">
                  <el-option label="现代" value="现代" />
                  <el-option label="古典" value="古典" />
                  <el-option label="未来" value="未来" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="类型" prop="type">
                <el-select v-model="localEquipment.type" placeholder="选择类型">
                  <el-option label="武器" value="武器" />
                  <el-option label="防具" value="防具" />
                  <el-option label="饰品" value="饰品" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="职业" prop="job">
                <el-select v-model="localEquipment.job" placeholder="选择职业">
                  <el-option label="血骑士" value="血骑士" />
                  <el-option label="圣牧师" value="圣牧师" />
                  <el-option label="影刺客" value="影刺客" />
                  <el-option label="通用" value="通用" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="6">
              <el-form-item label="部位" prop="solt">
                <el-select v-model="localEquipment.solt" placeholder="选择部位">
                  <el-option label="主手" value="主手" />
                  <el-option label="副手" value="副手" />
                  <el-option label="头部" value="头部" />
                  <el-option label="胸部" value="胸部" />
                  <el-option label="腿部" value="腿部" />
                  <el-option label="脚部" value="脚部" />
                  <el-option label="手部" value="手部" />
                  <el-option label="戒指" value="戒指" />
                  <el-option label="项链" value="项链" />
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="图标" prop="icon">
                <el-input 
                  v-model="localEquipment.icon" 
                  placeholder="图标路径或URL"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="表情符号" prop="emoji">
                <el-input 
                  v-model="localEquipment.emoji" 
                  placeholder="选择表情符号"
                >
                  <template #append>
                    <el-button @click="showEmojiPicker = true">
                      {{ localEquipment.emoji || '🔍' }}
                    </el-button>
                  </template>
                </el-input>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="描述">
            <el-input 
              v-model="localEquipment.desc" 
              type="textarea" 
              :rows="3"
              placeholder="输入装备描述"
            />
          </el-form-item>

          <el-form-item label="来源">
            <el-input 
              v-model="localEquipment.source" 
              placeholder="装备来源说明"
            />
          </el-form-item>

          <el-form-item label="启用状态">
            <el-switch 
              v-model="localEquipment.enabled"
              active-text="启用"
              inactive-text="禁用"
            />
          </el-form-item>
        </el-tab-pane>

        <!-- 品质配置 -->
        <el-tab-pane label="品质配置" name="quality">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="最低品质" prop="quality.min">
                <el-input-number 
                  v-model="localEquipment.quality.min"
                  :min="1"
                  :max="localEquipment.quality.max || 10"
                  controls-position="right"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="最高品质" prop="quality.max">
                <el-input-number 
                  v-model="localEquipment.quality.max"
                  :min="localEquipment.quality.min || 1"
                  :max="10"
                  controls-position="right"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="品质权重">
            <div class="quality-weights">
              <div 
                v-for="(weight, index) in qualityWeights" 
                :key="index"
                class="quality-weight-item"
              >
                <span class="quality-label">品质 {{ index + localEquipment.quality.min }}</span>
                <el-input-number 
                  v-model="qualityWeights[index]"
                  :min="0"
                  :max="100"
                  size="small"
                  controls-position="right"
                  @change="updateQualityWeights"
                />
                <span class="weight-percentage">
                  {{ getWeightPercentage(weight) }}%
                </span>
              </div>
            </div>
          </el-form-item>
        </el-tab-pane>

        <!-- 基础属性 -->
        <el-tab-pane label="基础属性" name="attributes">
          <div class="attributes-section">
            <div class="section-header">
              <h3>基础属性配置</h3>
              <el-button type="primary" size="small" @click="addAttribute">
                <el-icon><Plus /></el-icon>
                添加属性
              </el-button>
            </div>

            <div class="attributes-list">
              <div 
                v-for="(attr, index) in localEquipment.baseAttributes" 
                :key="index"
                class="attribute-item"
              >
                <el-card>
                  <div class="attribute-header">
                    <el-select 
                      v-model="attr.key" 
                      placeholder="选择属性"
                      style="width: 150px"
                    >
                      <el-option label="攻击力" value="attack" />
                      <el-option label="防御力" value="defense" />
                      <el-option label="生命值" value="health" />
                      <el-option label="魔法值" value="mana" />
                      <el-option label="暴击率" value="critical" />
                      <el-option label="暴击伤害" value="criticalDamage" />
                      <el-option label="命中率" value="accuracy" />
                      <el-option label="闪避率" value="dodge" />
                      <el-option label="移动速度" value="speed" />
                    </el-select>
                    <el-button 
                      type="danger" 
                      size="small" 
                      circle
                      @click="removeAttribute(index)"
                    >
                      <el-icon><Delete /></el-icon>
                    </el-button>
                  </div>

                  <el-row :gutter="10" style="margin-top: 12px;">
                    <el-col :span="8">
                      <el-form-item label="最小值" label-width="60px">
                        <el-input-number 
                          v-model="attr.min"
                          :min="0"
                          size="small"
                          controls-position="right"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="最大值" label-width="60px">
                        <el-input-number 
                          v-model="attr.max"
                          :min="attr.min"
                          size="small"
                          controls-position="right"
                        />
                      </el-form-item>
                    </el-col>
                    <el-col :span="8">
                      <el-form-item label="增长类型" label-width="80px">
                        <el-select v-model="attr.growthType" size="small">
                          <el-option label="线性" value="linear" />
                          <el-option label="指数" value="exponential" />
                          <el-option label="对数" value="logarithmic" />
                        </el-select>
                      </el-form-item>
                    </el-col>
                  </el-row>

                  <el-form-item label="品质系数" label-width="80px">
                    <el-input-number 
                      v-model="attr.qualityMultiplier"
                      :min="0.1"
                      :max="5"
                      :step="0.1"
                      size="small"
                      controls-position="right"
                    />
                  </el-form-item>
                </el-card>
              </div>
            </div>
          </div>
        </el-tab-pane>

        <!-- 技能配置 -->
        <el-tab-pane label="技能配置" name="skills">
          <SkillPoolsEditor 
            v-model="localEquipment.skillPools"
            @update="handleSkillPoolsUpdate"
          />
        </el-tab-pane>

        <!-- 元数据 -->
        <el-tab-pane label="元数据" name="metadata">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-form-item label="创建者">
                <el-input 
                  v-model="localEquipment.creator" 
                  placeholder="创建者姓名"
                />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="版本号">
                <el-input 
                  v-model="localEquipment.version" 
                  placeholder="版本号"
                />
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="标签">
            <el-tag
              v-for="tag in localEquipment.tags"
              :key="tag"
              closable
              @close="removeTag(tag)"
              style="margin-right: 8px; margin-bottom: 8px;"
            >
              {{ tag }}
            </el-tag>
            <el-input
              v-if="tagInputVisible"
              ref="tagInput"
              v-model="tagInputValue"
              size="small"
              style="width: 120px"
              @keyup.enter="handleTagInputConfirm"
              @blur="handleTagInputConfirm"
            />
            <el-button
              v-else
              size="small"
              @click="showTagInput"
            >
              <el-icon><Plus /></el-icon>
              添加标签
            </el-button>
          </el-form-item>
        </el-tab-pane>
      </el-tabs>

      <!-- 操作按钮 -->
      <div class="form-actions" v-if="mode === 'create'">
        <el-button @click="$emit('cancel')">取消</el-button>
        <el-button type="primary" @click="handleSubmit">创建装备</el-button>
      </div>
    </el-form>

    <!-- 表情符号选择器 -->
    <el-dialog v-model="showEmojiPicker" title="选择表情符号" width="400px">
      <div class="emoji-grid">
        <div 
          v-for="emoji in emojiList" 
          :key="emoji"
          class="emoji-item"
          @click="selectEmoji(emoji)"
        >
          {{ emoji }}
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, watch, nextTick } from 'vue'
import type { EquipmentTemplate, AttributeConfig } from '@/types/config'
import SkillPoolsEditor from './SkillPoolsEditor.vue'
import { Plus, Delete } from '@element-plus/icons-vue'

interface Props {
  equipment?: EquipmentTemplate
  mode?: 'edit' | 'create'
}

interface Emits {
  (e: 'update', id: string, updates: Partial<EquipmentTemplate>): void
  (e: 'create', equipment: EquipmentTemplate): void
  (e: 'cancel'): void
  (e: 'validate', equipment: EquipmentTemplate): void
}

const props = withDefaults(defineProps<Props>(), {
  mode: 'edit'
})

const emit = defineEmits<Emits>()

// 响应式数据
const formRef = ref()
const activeTab = ref('basic')
const showEmojiPicker = ref(false)
const tagInputVisible = ref(false)
const tagInputValue = ref('')
const tagInput = ref()

// 本地装备数据
const localEquipment = ref<EquipmentTemplate>({
  id: '',
  name: '',
  sys: '现代',
  type: '武器',
  job: '血骑士',
  solt: '主手',
  icon: '',
  emoji: '⚔️',
  quality: { min: 1, max: 5 },
  baseAttributes: [],
  skillPools: {
    inherent: [],
    enchantable: []
  },
  enabled: true,
  tags: [],
  ...props.equipment
})

// 品质权重数组
const qualityWeights = ref<number[]>([])

// 表单验证规则
const formRules = {
  id: [
    { required: true, message: '请输入装备ID', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9_-]+$/, message: 'ID只能包含字母、数字、下划线和连字符', trigger: 'blur' }
  ],
  name: [
    { required: true, message: '请输入装备名称', trigger: 'blur' }
  ],
  sys: [
    { required: true, message: '请选择体系', trigger: 'change' }
  ],
  type: [
    { required: true, message: '请选择类型', trigger: 'change' }
  ],
  job: [
    { required: true, message: '请选择职业', trigger: 'change' }
  ],
  solt: [
    { required: true, message: '请选择部位', trigger: 'change' }
  ]
}

// 表情符号列表
const emojiList = [
  '⚔️', '🗡️', '🏹', '🛡️', '👑', '💍', '📿', '🥾', '🧤',
  '⚡', '🔥', '❄️', '🌟', '💎', '🔮', '📜', '🧿', '💊'
]

// 计算属性
const totalWeight = computed(() => 
  qualityWeights.value.reduce((sum, weight) => sum + weight, 0)
)

// 方法
const updateQualityWeights = () => {
  localEquipment.value.quality.weights = [...qualityWeights.value]
  emitUpdate()
}

const getWeightPercentage = (weight: number) => {
  if (totalWeight.value === 0) return 0
  return Math.round((weight / totalWeight.value) * 100)
}

const addAttribute = () => {
  localEquipment.value.baseAttributes.push({
    key: '',
    min: 0,
    max: 100,
    growthType: 'linear',
    qualityMultiplier: 1.0
  })
  emitUpdate()
}

const removeAttribute = (index: number) => {
  localEquipment.value.baseAttributes.splice(index, 1)
  emitUpdate()
}

const selectEmoji = (emoji: string) => {
  localEquipment.value.emoji = emoji
  showEmojiPicker.value = false
  emitUpdate()
}

const removeTag = (tag: string) => {
  const index = localEquipment.value.tags?.indexOf(tag)
  if (index !== undefined && index > -1) {
    localEquipment.value.tags?.splice(index, 1)
    emitUpdate()
  }
}

const showTagInput = () => {
  tagInputVisible.value = true
  nextTick(() => {
    tagInput.value?.focus()
  })
}

const handleTagInputConfirm = () => {
  if (tagInputValue.value && !localEquipment.value.tags?.includes(tagInputValue.value)) {
    if (!localEquipment.value.tags) {
      localEquipment.value.tags = []
    }
    localEquipment.value.tags.push(tagInputValue.value)
    emitUpdate()
  }
  tagInputVisible.value = false
  tagInputValue.value = ''
}

const handleSkillPoolsUpdate = (skillPools: any) => {
  localEquipment.value.skillPools = skillPools
  emitUpdate()
}

const emitUpdate = () => {
  if (props.mode === 'edit' && props.equipment) {
    emit('update', props.equipment.id, localEquipment.value)
  }
}

const handleSubmit = async () => {
  if (!formRef.value) return
  
  try {
    await formRef.value.validate()
    emit('create', localEquipment.value)
  } catch (error) {
    console.error('表单验证失败:', error)
  }
}

// 初始化品质权重
const initQualityWeights = () => {
  const { min, max, weights } = localEquipment.value.quality
  const range = max - min + 1
  
  if (weights && weights.length === range) {
    qualityWeights.value = [...weights]
  } else {
    // 默认平均权重
    qualityWeights.value = new Array(range).fill(1)
  }
}

// 监听器
watch(() => props.equipment, (newEquipment) => {
  if (newEquipment) {
    localEquipment.value = { ...newEquipment }
    initQualityWeights()
  }
}, { immediate: true, deep: true })

watch(() => [localEquipment.value.quality.min, localEquipment.value.quality.max], () => {
  initQualityWeights()
}, { deep: true })

watch(() => localEquipment.value, () => {
  if (props.mode === 'edit') {
    emit('validate', localEquipment.value)
  }
}, { deep: true })
</script>

<style scoped>
.equipment-form {
  height: 100%;
}

.quality-weights {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.quality-weight-item {
  display: flex;
  align-items: center;
  gap: 12px;
}

.quality-label {
  width: 80px;
  font-weight: 500;
  color: var(--config-editor-text);
}

.weight-percentage {
  width: 50px;
  font-size: 12px;
  color: var(--config-editor-text-secondary);
}

.attributes-section {
  padding: 0;
}

.section-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.section-header h3 {
  margin: 0;
  color: var(--config-editor-text);
}

.attributes-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.attribute-item {
  border: 1px solid var(--config-editor-border);
  border-radius: 8px;
  overflow: hidden;
}

.attribute-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.form-actions {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  margin-top: 20px;
  padding: 20px;
  border-top: 1px solid var(--config-editor-border);
}

.emoji-grid {
  display: grid;
  grid-template-columns: repeat(6, 1fr);
  gap: 8px;
  padding: 16px;
}

.emoji-item {
  display: flex;
  justify-content: center;
  align-items: center;
  width: 40px;
  height: 40px;
  font-size: 20px;
  cursor: pointer;
  border-radius: 6px;
  transition: background-color 0.2s;
}

.emoji-item:hover {
  background-color: var(--config-editor-border);
}
</style>
